package org.example.day08;

/**
 * 第三章节3.1.17: 解决先notify后调用wait的情况
 */
public class MyThread4 {
    private String lock = new String("");
    private boolean isFirstRun = false;

    private Runnable runnable1 = new Runnable() {
        @Override
        public void run() {
            try {
                synchronized (lock){
                    while(isFirstRun == false){
                        System.out.println("wait begin time = " + System.currentTimeMillis());
                        lock.wait();
                        System.out.println("wait end time = " + System.currentTimeMillis());
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    private Runnable runnable2 = new Runnable() {
        @Override
        public void run() {
            synchronized (lock){
                System.out.println("notify begin time = " + System.currentTimeMillis());
                lock.notify();
                System.out.println("notify end time = " + System.currentTimeMillis());
                isFirstRun = true;
            }
        }
    };

    public static void main(String[] args) throws InterruptedException {
        MyThread4 m4 = new MyThread4();
        Thread tb = new Thread(m4.runnable2);
        tb.start();
        Thread.sleep(100); //线程2先拿到锁执行notify
        Thread ta = new Thread(m4.runnable1);
        ta.start();
    }
}
